<template>
  <div>
    <NavigationBar :navtitle="this.$route.query.id ? '资讯列表>资讯编辑' : '资讯列表>资讯发布'" @navEvent="navEvent"></NavigationBar>
    <div style="margin: 30px 140px">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="分类" >
          <el-cascader :options="typeList" v-model="ruleForm.categoryId" @change="setlectType">
          </el-cascader>
          <el-cascader :options="typeLists" :props="{ multiple: true }" v-model="ruleForm.categoryIds">
          </el-cascader>
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="ruleForm.status">
            <el-option label="有效" :value="1"></el-option>
            <el-option label="无效" :value="0"></el-option>
          </el-select>
          <div class="">
          </div>
        </el-form-item>
        
        <el-form-item label="活动：">
          <div>
            <el-radio v-model="ruleForm.activityFlag" :label="1">是</el-radio>
            <el-radio v-model="ruleForm.activityFlag" :label="0">否</el-radio>
          </div>
        </el-form-item>
        <el-form-item label="发布时间：">
          <el-date-picker value-format="timestamp" v-model="ruleForm.publicTime" type="datetime"
                placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="主推：">
          <div>
            <el-radio v-model="ruleForm.recommend" :label="1">是</el-radio>
            <el-radio v-model="ruleForm.recommend" :label="0">否</el-radio>
          </div>
          <div class="ztCont" v-if="ruleForm.recommend == 1">
            <div class="time">
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="ruleForm.matchTime" type="datetime"
                placeholder="选择日期时间">
              </el-date-picker>
            </div>
            <div class="time" style="margin-left:10px;">
              <el-input v-model="ruleForm.matchName" placeholder="请输入比赛名称"></el-input>
            </div>
            <div class="dwnr">
              <el-button v-if="ruleForm.teamOnePic == '' || ruleForm.teamOnePic == null" type="primary"
                @click="uploadHandle(2)">上传</el-button>
              <img class="Avatars" v-if="ruleForm.teamOnePic" :src="'https://qxbh5.oss-cn-guangzhou.aliyuncs.com' + ruleForm.teamOnePic"
                alt="" @click="uploadHandle(2)" />
              <el-input v-model="ruleForm.teamOne" placeholder="请输入"></el-input>
              <span>VS</span>
              <el-button v-if="ruleForm.teamTwoPic == '' || ruleForm.teamTwoPic == null" type="primary"
                @click="uploadHandle(3)">上传</el-button>
              <img class="Avatars" v-if="ruleForm.teamTwoPic" :src="'https://qxbh5.oss-cn-guangzhou.aliyuncs.com' + ruleForm.teamTwoPic"
                alt="" @click="uploadHandle(3)" />
              <el-input v-model="ruleForm.teamTwo" placeholder="请输入"></el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="留言积分" prop="title" class="lie">
          <el-input v-model="ruleForm.messageScore" type="number"  placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="初始阅读量" prop="title" class="lie">
          <el-input v-model="ruleForm.viewInitCount" type="number" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="资讯主图" prop="delivery">
          <el-button v-if="ruleForm.banner == '' || ruleForm.banner == null" type="primary"
            @click="uploadHandle(1)">上传</el-button>
          <img class="Avatars" v-if="ruleForm.banner" :src="'https://qxbh5.oss-cn-guangzhou.aliyuncs.com' + ruleForm.banner" alt=""
            @click="uploadHandle(1)" />
        </el-form-item>
        <el-form-item label="资讯详情" prop="content">
          <vue-editor v-model="ruleForm.content" placeholder="详情" id="editor" useCustomImageHandler
            @image-added="handleImageAdded"></vue-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="dataFormSubmit()" >{{ id ? '修改' : '发布' }} </el-button>
        </el-form-item>
      </el-form>
    </div>
    <upload v-if="uploadVisible" ref="upload" :uploadList="uploadList"></upload>
  </div>
</template>

<script>
import Upload from './oss-upload'
import { VueEditor } from 'vue2-editor'
export default {
  components: {
    NavigationBar: () => import('../../components/navigationBar/index.vue'),
    Upload,
    VueEditor
  },
  data () {
    return {
      eIndex: '',
      isdisabled: false,
      uploadVisible: false,
      typeList: [],
      typeLists: [],
      ruleForm: {
        activityFlag: 0,
        categoryId: '',
        categoryIds: '',
        content: '',
        publicTime: '',
        banner: '',
        status: 1,
        title: '',
        matchName: '',
        recommend: 0,
        messageScore: '',
        viewInitCount: '',
        matchTime: '',
        teamOne: '',
        teamTwo: '',
        teamOnePic: '',
        teamTwoPic: ''
      },
      id: '',
      rules: {
        title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
        banner: [{ required: true, message: '请上传图片', trigger: 'blur' }],
        content: [{ required: true, message: '请填写内容', trigger: 'blur' }]
      },
      // headers:{}
      uploadAction: '',
      imageUrl: ''

    }
  },
  activated () {
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.getDataDetails()
    } else {
      this.$refs['ruleForm'].resetFields()
      this.ruleForm = {
        categoryId: '',
        categoryIds: '',
        content: '',
        publicTime: '',
        banner: '',
        status: 1,
        activityFlag: 0,
        title: '',
        matchName: '',
        recommend: 0,
        messageScore: '',
        viewInitCount: '',
        matchTime: '',
        teamOne: '',
        teamTwo: '',
        teamOnePic: '',
        teamTwoPic: ''
      }
      this.id = ''
    }
  },
  created () {
    this.getDataDetails()
    // this.goodsTagList()
    this.getCategory()
    // if(this.$route.query.id){
    //   this.getDataDetails()
    // }
  },
  mounted () {
    this.ue = ueditor.getEditor(this.ueId, {
      // serverUrl: '', // 服务器统一请求接口路径
      zIndex: 3000
    })
  },
  methods: {
    setlectType () {
      this.typeList.forEach((item, index) => {
        if (item.id == this.ruleForm.categoryId[0]) {
          this.typeLists = item.childs
        }
      })
    },
    getCategory () {
      this.$http({
        url: this.$http.adornUrl(`/common/back/category/list`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === '200') {
          let list = data.list
          list.forEach((item, index) => {
            item.label = item.categoryName
            item.value = item.id
            item.childs.forEach((i, x) => {
              i.label = i.categoryName
              i.value = i.id
            })
            // item.children = item.goodsTagList
          })
          this.typeList = list
        }
      })
    },
    uploadHandle (e) {
      this.uploadVisible = true
      this.eIndex = e
      this.$nextTick(() => {
        this.$refs.upload.init()
      })
    },
    uploadList (e) {
      if (this.eIndex == 1) {
        this.ruleForm.banner = e.trim()
      } else if (this.eIndex == 2) {
        this.ruleForm.teamOnePic = e.trim()
      } else if (this.eIndex == 3) {
        this.ruleForm.teamTwoPic = e.trim()
      }
    },
    handleImageAdded: function (file, Editor, cursorLocation, resetUploader) {
      // An example of using FormData
      // NOTE: Your key could be different such as:
      // formData.append('file', file)

      var formData = new FormData()

      formData.append('file', file)
      //  console.log(file)
      this.$http({
        url: this.$http.adornUrl('/common/file/upload'),
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        data: formData
      }).then(({ data }) => {
        if (data && data.code === '200') {
          Editor.insertEmbed(cursorLocation, 'image', 'https://qxbh5.oss-cn-guangzhou.aliyuncs.com' + data.data)
          resetUploader()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      let id = {}
      this.$refs['ruleForm'].validate((valid) => {
        // if (typeof (this.ruleForm.categoryId) === 'string') {
        //   this.ruleForm.categoryId = this.ruleForm.categoryId
        // } else {
        //   if (this.ruleForm.categoryId[1]) {
        //     this.ruleForm.categoryId = this.ruleForm.categoryId[1]
        //   } else {
        //     this.ruleForm.categoryId = this.ruleForm.categoryId[0]
        //   }
        // }
        id.id = Number(this.id)
        this.isdisabled = true
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(this.id ? '/admin/information/update' : `/admin/information/add`),
            method: this.id ? 'post' : 'post',
            data: this.$http.adornData({
              matchName: this.ruleForm.matchName,
              teamOne: this.ruleForm.teamOne,
              teamTwo: this.ruleForm.teamTwo,
              teamOnePic: this.ruleForm.teamOnePic,
              teamTwoPic: this.ruleForm.teamTwoPic,
              categoryId: this.ruleForm.categoryId + '',
              categoryIds: this.ruleForm.categoryIds ? this.ruleForm.categoryIds.join(',') : '',
              content: this.ruleForm.content,
              banner: this.ruleForm.banner,
              activityFlag: this.ruleForm.activityFlag,
              recommend: this.ruleForm.recommend,
              status: this.ruleForm.status,
              title: this.ruleForm.title,
              messageScore: this.ruleForm.messageScore,
              viewInitCount: this.ruleForm.viewInitCount,
              matchTime: this.ruleForm.matchTime,
              publicTime: this.ruleForm.publicTime,
              ...id
            })
          }).then(({ data }) => {
            if (data && data.code === '200') {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.$router.push({ name: 'i-informationList' })
                }
              })
            } else {
              this.$message.error(data.msg)
            }
            this.isdisabled = false
          })
        }
      })
    },
    // 获取数据列表
    getDataDetails () {
      var id = this.$route.query.id
      this.$http({
        url: this.$http.adornUrl(
          `/admin/information/view?id=${id}`
        ),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === '200') {
          this.ruleForm.categoryId = [data.data.categoryId]
          this.setlectType()
          this.ruleForm.title = data.data.title
          this.ruleForm.matchName = data.data.matchName
          this.ruleForm.content = data.data.content
          this.ruleForm.status = data.data.status
          this.ruleForm.banner = data.data.banner
          this.ruleForm.recommend = data.data.recommend
          this.ruleForm.categoryIds = data.data.categoryIds.split(',')
          this.ruleForm.viewInitCount = data.data.viewInitCount
          this.ruleForm.messageScore = data.data.messageScore
          this.ruleForm.matchTime = data.data.matchTime
          this.ruleForm.activityFlag = data.data.activityFlag
          this.ruleForm.teamOne = data.data.teamOne
          this.ruleForm.teamTwo = data.data.teamTwo
          this.ruleForm.teamOnePic = data.data.teamOnePic
          this.ruleForm.teamTwoPic = data.data.teamTwoPic
          this.ruleForm.publicTime = data.data.publicTime
        } else {
        }
      })
    },
    navEvent () {
      this.$router.push({ name: 'i-informationList' })
    }
  }
}
</script>

<style lang="scss">
.ql-editor {
  max-height: 320px !important;
}

.ztCont {
  display: flex;

  .dwnr {
    display: flex;

    .el-button {
      margin: 0 10px;
    }

    span {
      margin-left: 10px;
    }

    .Avatars {
      margin: 0 10px;
      width: 40px;
      height: 40px;
    }
  }
}

.Avatars {
  width: 100px;
  height: 100px;
}

.el-scrollbar__wrap {
  overflow: auto !important;
  margin-bottom: 0px !important;
  margin-right: 0px !important;
  height: 100% !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.mod-demo-ueditor {
  position: relative;
  z-index: 510;

  >.el-alert {
    margin-bottom: 10px;
  }
}</style>